import express from "express";
import cors from "cors";
import bodyParser from "body-parser";
import { getTimeline, getGuestToken, format } from "./twitterApi";

let app = express();

app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(express.static("./web"));

app.post("/token", async (req, res) => {
  const token = await getGuestToken();
  res.end(token);
});

app.post("/twTimeline", async (req, res) => {
  const { upname } = req.body as { upname: string };

  try {
    const count = 100;
    const token = await getGuestToken();
    const data = format(await getTimeline(upname, count, token));
    let arr: string[] = [];
    arr.push(...data.photos.map((n) => n.url));
    arr.push(...data.videos.map((n) => n.url));
    res.json({ urls: arr });
  } catch (e) {
    console.log(e);
    res.json({ urls: null });
  }
});

app.get("/test", (req, res) => {
  res.end("tw timeline test successful");
});

app.listen(3000, () => {
  console.log("server launch ...");
});
